package cn.com.bluemoon.daps.common.datascope.handler;

import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.exception.DapException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 本类针对前端请求后端过程中，进行数据校验，若不合法则捕获进行异常处理，然后返回给前端
 * 而{@see ControllerAop} 是对系统业务逻辑的异常进行处理，然后返回给前端
 */
@Slf4j
@RestControllerAdvice
@ConditionalOnProperty(
        value = {"bm.dap.http.auth.enable"},
        matchIfMissing = true
)
public class DapsGlobalExceptionHandler {
    @Value("${spring.servlet.multipart.max-file-size:10M}")
    private String maxFileSize;

//    @ExceptionHandler({MaxUploadSizeExceededException.class, FileUploadBase.FileSizeLimitExceededException.class})
//    public void handlerMaxUploadFile(RuntimeException ex){
//        log.error("文件上传失败：", ex);
//        throw new DapThrowException("文件上传大小不超过" + maxFileSize);
//    }

    @ExceptionHandler(value = DapException.class)
    public ResultBean<String> method(HttpServletRequest req, DapException ex) {
        ResultBean<String> result = ResultBean.FAIL;
        String errorMsg = ex.getMessage();
        log.error("---DapException Handler--- ERROR: {}", errorMsg);
        result.setMsg(errorMsg);
        result.setCode(ex.getCode());
        return result;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBean<String> methodArgumentNotValid(HttpServletRequest req, MethodArgumentNotValidException ex) {
        ResultBean<String> result = ResultBean.FAIL;
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        String errorMsg = errors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).distinct().collect(Collectors.joining(";"));
        log.error("---MethodArgumentNotValidException Handler--- ERROR: {}", errorMsg);
        result.setMsg(errorMsg);
        return result;
    }
}
